<?php

namespace app\admin\controller\community\config;

use app\common\controller\Backend;
use think\Db;
use think\db\Raw;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\community\project\Setcourse as SetcourseModel;
/**
 * 课程代码配置管理
 *
 * @icon fa fa-book
 */
class Course extends Backend
{
    /**
     * Course模型对象
     * @var \app\admin\model\community\config\Course
     */
    protected $model = null;
    protected $noNeedRight = ['del'];
    protected $noNeedLogin = ['del'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\community\config\Course;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            $searchFields = ['id', 'code', 'name', 'remark'];
            $sortFields = ['id', 'code', 'name', 'community_id', 'publicwelfare_id', 'status', 'weigh', 'createtime', 'updatetime'];
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams($sortFields, $searchFields);
            $where = [];
            // 获取URL中传递的参数
            $community_id = $this->request->param('community_id', 0);
            $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
            
            // 如果有传递参数，则添加到查询条件中
            if ($community_id > 0) {
                $where['fa_community_course_config.community_id'] = $community_id;
            }
            if ($publicwelfare_id > 0) {
                $where['fa_community_course_config.publicwelfare_id'] = $publicwelfare_id;
            }

            // 检查是否需要自动生成课程代码
            $this->autoGenerateCourseCode($community_id, $publicwelfare_id);

            // 按照community_id和publicwelfare_id条件和ID顺序，重新生成code字段的值,值如 C1、C2、C3...按顺序修改记录code字段的值
            Db::execute("SET @rownum = 0");
            $this->model->where($where)->order('id')->update(['code' => Db::raw("CONCAT('C', @rownum := @rownum + 1)")]);

            
            $list = $this->model
                ->with(['community', 'publicwelfare'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            
            return json($result);
        }
        
        // 获取URL中传递的参数并传递给视图
        $community_id = $this->request->param('community_id', 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 从URL参数中获取community_id和publicwelfare_id
                $community_id = $this->request->param('community_id', 0);
                $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
                
                // 如果表单没有提交这些值，但URL中有，则自动填充
                if (!isset($params['community_id']) && $community_id > 0) {
                    $params['community_id'] = $community_id;
                }
                if (!isset($params['publicwelfare_id']) && $publicwelfare_id > 0) {
                    $params['publicwelfare_id'] = $publicwelfare_id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);
        
        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);


        
        // 获取当前用户所属社区和URL参数
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 查询未被选取的课程列表
        $courseList = [];
        if ($community_id > 0 && $publicwelfare_id > 0) {
            // 查询已经配置的课程代码
            $existingNames = $this->model
                ->where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->column('name');
            
            // 查询所有可用的课程
            $allCourses = SetcourseModel::where('community_id', $community_id)->where('publicwelfare_id', $publicwelfare_id)->select();
            $courseList = [];
            // 过滤出未被选取的课程
            foreach ($allCourses as $course) {
                // 使用course_code字段代替原来的code字段
                $courseName = isset($course['course_name']) ? $course['course_name'] : $course['id'];
                if (!in_array($courseName, $existingNames)) {
                    $courseName = isset($course['course_name']) ? $course['course_name'] : ($course['course_name'] ?? 'Unknown');
                    // 使用课程名称作为键和值，确保在视图中正确传递
                    $courseList[$courseName] = $courseName;
                }
            }
        }
        $this->view->assign('courseList', $courseList);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取社区列表
        $communityList = \app\admin\model\Community::where('status', 1)->column('name', 'id');
        $this->view->assign('communityList', $communityList);
        
        // 获取公益项目列表
        $publicwelfareList = \app\admin\model\community\Publicwelfare::where('status', 1)->column('project_name', 'id');
        $this->view->assign('publicwelfareList', $publicwelfareList);
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        
        // 查询已经配置的课程名称
        $existingNames = $this->model
            ->where('community_id', $community_id)
            ->where('publicwelfare_id', $publicwelfare_id)
            ->column('name');
            
        // 查询所有可用的课程
        $allCourses = SetcourseModel::where('community_id', $community_id)->where('publicwelfare_id', $publicwelfare_id)->select();
        $courseList = [];
        
        // 过滤出未被选取的课程和当前课程
        foreach ($allCourses as $course) {
            // 使用course_name字段
            $courseName = isset($course['course_name']) ? $course['course_name'] : $course['id'];
            if (!in_array($courseName, $existingNames) || $courseName == $row['name']) {
                $courseName = isset($course['course_name']) ? $course['course_name'] : ($course['course_name'] ?? 'Unknown');
                // 使用课程名称作为键和值，确保在视图中正确传递
                $courseList[$courseName] = $courseName;
            }
        }
        
        // 获取URL参数和当前用户所属社区
        $user = $this->auth->getUserInfo();
        $community_id = $this->request->param('community_id', $user['community_id'] ?? 0);
        $publicwelfare_id = $this->request->param('publicwelfare_id', 0);
        $this->view->assign('community_id', $community_id);
        $this->view->assign('publicwelfare_id', $publicwelfare_id);
        
        // 查询课程列表，包括当前课程和未被选取的课程
        $courseList = [];
        if ($community_id > 0 && $publicwelfare_id > 0) {
            // 查询已经配置的课程代码（排除当前课程）
            $existingCodes = $this->model
                ->where('community_id', $community_id)
                ->where('publicwelfare_id', $publicwelfare_id)
                ->where('id', '<>', $ids) // 排除当前课程
                ->column('code');
            
            // 查询所有可用的课程
            $allCourses = \app\admin\model\Course::where('status', 1)->select();
            
            // 过滤出未被选取的课程和当前课程
            foreach ($allCourses as $course) {
                // 使用course_code字段代替原来的code字段
                $courseCode = isset($course['course_code']) ? $course['course_code'] : $course['id'];
                if (!in_array($courseCode, $existingCodes) || $courseCode == $row['code']) {
                    $courseName = isset($course['title']) ? $course['title'] : ($course['name'] ?? 'Unknown');
                    $courseList[$courseCode] = $courseName . ' (' . $courseCode . ')';
                }
            }
        }
        $this->view->assign('courseList', $courseList);
        
        // 如果通过网址传入了community_id和publicwelfare_id，则设置一个标记，用于控制视图中的字段显示
        $simplifiedView = ($community_id > 0 || $publicwelfare_id > 0);
        $this->view->assign('simplifiedView', $simplifiedView);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 自动生成课程代码
     * 如果项目的课程代码为空，从课程表中列出所有课程，并自动生成代码（C1, C2, C3...）
     * @param int $communityId 社区ID
     * @param int $publicwelfareId 公益项目ID
     */
    protected function autoGenerateCourseCode($communityId, $publicwelfareId)
    {
        if (empty($communityId) || empty($publicwelfareId)) {
            return;
        }
        
        // 检查该项目是否已有课程代码配置
        $existingCodes = $this->model
            ->where('community_id', $communityId)
            ->where('publicwelfare_id', $publicwelfareId)
            ->count();
        
        // 如果已有课程代码配置，则不需要自动生成
        if ($existingCodes > 0) {
            return;
        }
        
        // 从项目课程表中获取所有课程
        $courses = \app\admin\model\community\project\Setcourse::where('community_id', $communityId)
            ->where('publicwelfare_id', $publicwelfareId)
            ->select();
        
        if (empty($courses)) {
            return;
        }
        
        // 为每个课程生成代码并插入记录
        $index = 1;
        foreach ($courses as $course) {
            // 生成课程代码 C1, C2, C3...
            $code = 'C' . $index;
            
            // 插入新记录
            $data = [
                'community_id' => $communityId,
                'publicwelfare_id' => $publicwelfareId,
                'code' => $code,
                'name' => $course['course_name'],
                'intro' => $course['course_description'],
                'cover' => $course['course_image'],
                'setcourese_id' => $course['id'],
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ];
            
            $this->model->insert($data);
            $index++;
        }
    }
    
    /**
     * 重新排序课程代码
     * 当用户删除了某条记录，重新为剩余记录生成连续的代码
     * @param int $communityId 社区ID
     * @param int $publicwelfareId 公益项目ID
     */
    /**
     * 重新排序课程代码
     * @param int $communityId 社区ID
     */
    /**
     * 重新排序课程代码
     * @param int $communityId 社区ID
     */
    protected function reorderCourseCode($communityId)
    {
        // 获取该社区的所有课程代码记录
        $records = $this->model->where('community_id', $communityId)->order('id asc')->select();

        // 重新生成课程代码
        $index = 1;
        foreach ($records as $record) {
            $record->code = 'C' . $index;
            $record->save();
            $index++;
        }
    }
    
    function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        try {
            // 获取要删除的记录，以便获取其community_id和publicwelfare_id
            $records = $this->model->where('id', 'in', $ids)->select();
            $communityIds = [];
            $publicwelfareIds = [];
            
            foreach ($records as $record) {
                $communityIds[] = $record['community_id'];
                $publicwelfareIds[] = $record['publicwelfare_id'];
            }
            
            // 强制删除记录
            $result = $this->model->where('id', 'in', $ids)->delete();
            
            if ($result) {
                // 对每个community_id和publicwelfare_id组合重新生成课程代码
                $uniquePairs = array_unique(array_map(function($c, $p) {
                    return $c . '-' . $p;
                }, $communityIds, $publicwelfareIds));
                
                foreach ($uniquePairs as $pair) {
                    list($communityId, $publicwelfareId) = explode('-', $pair);
                    $this->reorderCourseCode($communityId, $publicwelfareId);
                }
                
                // 使用FastAdmin框架标准的成功返回格式
                return json(['code' => 1, 'msg' => __('Delete successful')]);
                //$this->success(__('Delete successful'));
            } else {
                $this->error(__('No rows were deleted'));
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

}
